<template>
  <div class="search-form">
    <el-form ref="formRef" label-position="left" :model="formData" inline v-bind="$attrs">
      <el-row :gutter="10">
        <el-col v-bind="item.layout" v-for="item in fileds" :key="item.key">
          <div class="flex-rowl">
            <div class="lable" :class="isRequired(item) ? 'required' : ''" :style="{ width: `${item.titleWidth}px` }">{{
              item.title }}</div>
            <el-form-item v-bind="item.itemProps" class="search-item">
              <template v-if="item.filedType === 'custom'">
                <slot :name="item.key" />
              </template>
              <template v-else>
                <component :is="item.filedType" size="small" v-bind="item.props" clearable
                  v-model="formData[item.key]" />
              </template>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col>
        <slot name="operate"></slot>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import Input from "./components/Input.vue"
import Select from "./components/Select.vue"
import DatePicker from "./components/DatePicker.vue"
export default {
  components: { Input, Select, DatePicker },
  props: {
    fileds: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      formData: {}
    }
  },
  computed: {
    isRequired() {
      return function (item) {
        if (!item.itemProps) return false
        if (!item.itemProps.rules) return false
        if (item.itemProps.rules.length === 0) return false
        if (item.itemProps.rules.some(rule => rule.required)) return true
        return false
      }
    }
  },
  methods: {
    handleSearch() {
      this.$emit('onSearch', this.formData)
    },
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.formRef.validate(valid => {
          if (valid) {
            resolve(this.formData)
          } else {
            reject(false)
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.search-form {
  border: 1px solid #CFCCCC;
}

.flex-rowl {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1px solid #CFCCCC;

  .lable {
    line-height: 38px;
    text-align: right;
    padding-right: 15px;
  }
}

.required {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  &::before {
    content: "*";
    color: red;
    margin-right: 5px;
    margin-top: 5px;
  }
}
</style>
